package com.java.time.example;

import java.time.LocalDate;
import java.util.Calendar;
import java.util.Scanner;

/**
 * 万年历
 */
public class PerpetualCalendar {
    public static void calendarAccomplish(int year, int month) {
        // 获取Calendar实例并设置年份
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);

        // 获取当月的天数：下月的第0天即当月最后一天
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        int totalDay = calendar.get(Calendar.DAY_OF_MONTH);

        // 获取当月1号星期几
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int oneDayWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;

        System.out.println("一\t二\t三\t四\t五\t六\t天");
        for (int i = 0; i < oneDayWeek - 1; i++) {
            System.out.print("-\t");
        }

        for (int i = 0; i < totalDay; i++) {
            System.out.print(i + 1 + "\t");
            if ((oneDayWeek + i) % 7 == 0) {
                System.out.println();
            }
        }
    }

    public static void localDateAccomplish(int year, int month) {
        LocalDate localDate = LocalDate.of(year, month, 1);

        // 获取当月的天数
        localDate = localDate.plusMonths(1).minusDays(1);
        int totalDay = localDate.getDayOfMonth();

        // 获取当月1号星期几
        localDate = localDate.withDayOfMonth(1);
        int oneDayWeek = localDate.getDayOfWeek().getValue();

        System.out.println("一\t二\t三\t四\t五\t六\t天");
        for (int i = 0; i < oneDayWeek - 1; i++) {
            System.out.print("-\t");
        }

        for (int i = 0; i < totalDay; i++) {
            System.out.print(i + 1 + "\t");
            if ((oneDayWeek + i) % 7 == 0) {
                System.out.println();
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int year = 0;
        int month = 0;
        do {
            System.out.print("请输入年份：");
            year = sc.nextInt();
        } while (year < 1900);
        do {
            System.out.print("请输入月份：");
            month = sc.nextInt();
        } while (month > 12 || month < 1);

        calendarAccomplish(year, month);
        System.out.println();
        localDateAccomplish(year, month);
    }
}
